package elitech.vietnam.copyweatherfashion;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParserException;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.copyweatherfashion.CreatePostActivity.CreateType;
import elitech.vietnam.copyweatherfashion.badge.BadgeHelper;
import elitech.vietnam.copyweatherfashion.config.Config;
import elitech.vietnam.copyweatherfashion.config.Options;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.ConfirmDialogClick;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.Type;
import elitech.vietnam.copyweatherfashion.dialog.EditDialogFragment;
import elitech.vietnam.copyweatherfashion.dialog.EditDialogFragment.ActionSelectListener;
import elitech.vietnam.copyweatherfashion.dialog.GetImageDialogFragment;
import elitech.vietnam.copyweatherfashion.dialog.GetImageDialogFragment.GetImageChoosen;
import elitech.vietnam.copyweatherfashion.dialog.GetImageDialogFragment.ListenerType;
import elitech.vietnam.copyweatherfashion.dialog.NotifyWindow;
import elitech.vietnam.copyweatherfashion.dialog.ProgressDialogFragment;
import elitech.vietnam.copyweatherfashion.entities.Member;
import elitech.vietnam.copyweatherfashion.entities.Notify;
import elitech.vietnam.copyweatherfashion.entities.Post;
import elitech.vietnam.copyweatherfashion.fragments.BaseFragment;
import elitech.vietnam.copyweatherfashion.fragments.MemberPostFragment;
import elitech.vietnam.copyweatherfashion.fragments.settings.FriendListFragment;
import elitech.vietnam.copyweatherfashion.gcm.GCMIntentService;
import elitech.vietnam.copyweatherfashion.location.MyLocation;
import elitech.vietnam.copyweatherfashion.prefs.PrefsDefinition;
import elitech.vietnam.copyweatherfashion.utilities.MyCallable;
import elitech.vietnam.copyweatherfashion.utilities.ServerClock;
import elitech.vietnam.copyweatherfashion.utilities.Utilities;
import elitech.vietnam.copyweatherfashion.weather.objects.WeatherObject;
import elitech.vietnam.copyweatherfashion.wsclient.Service;

public class MainActivity extends FragmentActivity implements ConfirmDialogClick, OnTabChangeListener, View.OnClickListener, GetImageChoosen, ActionSelectListener {

	public static final String	TAB_TODAY					= "TF";
	public static final String	TAB_WEEKLY					= "WF";
	public static final String	TAB_STYLER					= "TS";
	public static final String	TAB_SELF					= "MF";
	public static final String	TAB_SETTINGS				= "ST";

	public static final String	ACTION_UPDATEBADGE			= "elitech.vietnam.copyweatherfashion.ACTION_UPDATEBADGE";

	public static final String	EXTRAS_TABRESUME			= "EXTRAS_TABRESUME";
	public static final String	EXTRAS_NOTIFYDATA			= "EXTRAS_NOTIFYDATA";

	public static final int		REQUEST_LIBRARY				= 1;
	public static final int		REQUEST_CAMERA				= 2;
	public static final int		REQUEST_LOGIN				= 3;
	public static final int		REQUEST_EDITCAMERA			= 4;
	public static final int		REQUEST_EDITLIBRARY			= 5;
	public static final int		REQUEST_EDITCROP			= 6;
	public static final int		REQUEST_CROP				= 7;
	public static final int		REQUEST_EDITPOST			= 8;
	public static final int		REQUEST_NEWPOST				= 9;

	public Config				mConfig;
	public SharedPreferences	mPrefs;
	public Options				mOptions;
	public ServerClock			mClock;

	public FragmentTabHost		mTabHost;

	public TextView				mTxtTitle, mTxtBadge;
	public ImageButton			mBtnBack, mBtnEdit, mBtnCamera;
	public RelativeLayout		mBtnNotify;
	public NotifyWindow			mNotiWindow;
	public Button				mBtnSaveProfile;

	public Member				mUser;
	public List<Post>			mTodayList					= new ArrayList<>();
	public List<Post>			mWeeklyList1				= new ArrayList<>();
	public List<Post>			mWeeklyList2				= new ArrayList<>();
	public List<Post>			mWeeklyList3				= new ArrayList<>();
	public List<Post>			mWeeklyList4				= new ArrayList<>();
	public List<Post>			mWeeklyList5				= new ArrayList<>();
	public List<Post>			mStylerList1				= new ArrayList<>();
	public List<Post>			mStylerList2				= new ArrayList<>();
	public List<Post>			mSelfList1					= new ArrayList<>();
	public List<Post>			mSelfList2					= new ArrayList<>();
	public List<Member>			mFriendList1				= new ArrayList<>();
	public List<Member>			mFriendList2				= new ArrayList<>();
	public List<Notify>			mListNotify					= new ArrayList<>();
	public Post					mStylePost					= new Post();
	public Post					mShopPost					= new Post();

	public WeatherObject		mWeather;
	public MyLocation			mLocation;

	int							mPrevTab					= 0;
	boolean						isBack						= false;

	public Intent				mResultIntent;
	public int					mRequestCode				= -1;
	public int					mBadgeCount					= 0;
	
	public int					mTdImgWidth					= 0;
	public int					mTdImgHeigh					= 0;
	
	private BroadcastReceiver	mBadgeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			mBadgeCount += 1;
			Notify mNotify = new Gson().fromJson(intent.getStringExtra(MainActivity.EXTRAS_NOTIFYDATA), Notify.class);
			mListNotify.add(0, mNotify);
			notifyBadgeChanged();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		UrlImageViewHelper.setUseBitmapScaling(true);
		Log.w(getClass().getSimpleName(), "onCreate");
		/**
		 * Setup configuration, shared preferences...
		 */
		mConfig = new Config(this);
		mPrefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);

		/**
		 * Initialize options
		 */
		mClock = new Gson().fromJson(mPrefs.getString(PrefsDefinition.TIMESYNC, ""), ServerClock.class);
		mOptions = new Gson().fromJson(mPrefs.getString(PrefsDefinition.OPTION, ""), Options.class);
		if (mOptions == null) {
			mOptions = new Options();
			mPrefs.edit().putString(PrefsDefinition.OPTION, new Gson().toJson(mOptions)).commit();
		}
		/**
		 * Get data
		 */
		mUser = new Gson().fromJson(mPrefs.getString(PrefsDefinition.USER, ""), Member.class);
		mLocation = new Gson().fromJson(mPrefs.getString(PrefsDefinition.LOCATION, ""), MyLocation.class);
		mWeather = new Gson().fromJson(mPrefs.getString(PrefsDefinition.WEATHER, ""), WeatherObject.class);
		mBadgeCount = mPrefs.getInt(PrefsDefinition.BADGECOUNT, 0);

		/**
		 * Auto login
		 */
		if (mUser != null)
			new AsyncTask<Integer, Integer, Boolean>() {
				String gcm = Utilities.getRegistrationId(getApplicationContext());
				@Override
				protected Boolean doInBackground(Integer... params) {
					try {
						return new Service().updateGCM(mUser.Id, gcm) > 0;
					} catch (IOException | XmlPullParserException e) {
						e.printStackTrace();
					}
					return false;
				}
				@Override
				protected void onPostExecute(Boolean result) {
					if (!result) {
						Toast.makeText(MainActivity.this, "Auto login failed. Please login from Settings", Toast.LENGTH_SHORT).show();
						mUser = null;
						mPrefs.edit().putString(PrefsDefinition.USER, "").commit();
					} else {
						mUser.GcmId = gcm;
						mPrefs.edit().putString(PrefsDefinition.USER, new Gson().toJson(mUser)).commit();
					}
				}
			}.execute();
		
		/**
		 * Register receivers
		 */
		registerReceiver(mBadgeReceiver, new IntentFilter(ACTION_UPDATEBADGE));

		/**
		 * Setup Tab host
		 */
		mTabHost = (FragmentTabHost) findViewById(R.id.main_tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.main_tabcontent);

		mTabHost.addTab(
				mTabHost.newTabSpec(TAB_TODAY).setIndicator(
						createTabView(R.drawable.ic_today, R.drawable.maintabview_today)), BaseFragment.class,
				BaseFragment.newArs(TAB_TODAY));
		mTabHost.addTab(
				mTabHost.newTabSpec(TAB_WEEKLY).setIndicator(
						createTabView(R.drawable.ic_weekly, R.drawable.maintabview_weekly)), BaseFragment.class,
				BaseFragment.newArs(TAB_WEEKLY));
		mTabHost.addTab(
				mTabHost.newTabSpec(TAB_STYLER).setIndicator(
						createTabView(R.drawable.ic_styler, R.drawable.maintabview_styler)), BaseFragment.class,
				BaseFragment.newArs(TAB_STYLER));
		mTabHost.addTab(
				mTabHost.newTabSpec(TAB_SELF).setIndicator(
						createTabView(R.drawable.ic_self, R.drawable.maintabview_self)), BaseFragment.class,
				BaseFragment.newArs(TAB_SELF));
		mTabHost.addTab(
				mTabHost.newTabSpec(TAB_SETTINGS).setIndicator(
						createTabView(R.drawable.ic_settings, R.drawable.maintabview_setting)), BaseFragment.class,
				BaseFragment.newArs(TAB_SETTINGS));
		
		for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
			final int index = i;
			mTabHost.getTabWidget().getChildAt(i).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mTabHost.getCurrentTab() != index)
						mTabHost.setCurrentTab(index);
					else
						getCurrentBase().popAllFragment();
				}
			});
		}
		
		/**
		 * Initialize notification window
		 */
		mNotiWindow = new NotifyWindow(this);
		mNotiWindow.setContentView(LayoutInflater.from(this).inflate(R.layout.notification_window, null));
		mNotiWindow.setWidth(LayoutParams.MATCH_PARENT);
		mNotiWindow.setHeight(LayoutParams.MATCH_PARENT);
		mNotiWindow.setFocusable(true);

		/**
		 * Get all main view
		 */
		mTxtTitle = (TextView) findViewById(R.id.main_txtHeader);
		mTxtBadge = (TextView) findViewById(R.id.btnnoti_text);
		mBtnBack = (ImageButton) findViewById(R.id.main_btnBack);
		mBtnCamera = (ImageButton) findViewById(R.id.main_btnCamera);
		mBtnEdit = (ImageButton) findViewById(R.id.main_btnEdit);
		mBtnNotify = (RelativeLayout) findViewById(R.id.main_btnNotify);
		mBtnSaveProfile = (Button) findViewById(R.id.main_btnSaveProfile);

		/**
		 * Assign listener
		 */
		mTabHost.setOnTabChangedListener(this);
		mBtnBack.setOnClickListener(this);
		mBtnCamera.setOnClickListener(this);
		mBtnEdit.setOnClickListener(this);
		mBtnNotify.setOnClickListener(this);
		
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				notificationClicked(getIntent());
			}
		}, 500);
	}

	@Override
	protected void onStart() {
		super.onStart();
		/**
		 * Update the language
		 */
		changeLanguage(mOptions.mLanguage);
	}
	/**
	 * Create main tab view
	 * 
	 * @param resId
	 * @param bgId
	 * @return
	 */
	private View createTabView(int resId, int bgId) {
		ImageView view = (ImageView) LayoutInflater.from(this).inflate(R.layout.main_tabview, null);
		view.setBackgroundResource(bgId);
		view.setImageResource(resId);
		return view;
	}

	/**
	 * When hardware back button pressed
	 */
	@Override
	public void onBackPressed() {
		String curTab = mTabHost.getCurrentTabTag();
		boolean isPop = false;
		/**
		 * Pop fragment
		 */
		BaseFragment base = getCurrentBase();
		if (base != null)
			isPop = base.popFragment();
		/**
		 * Return to Today
		 */
		if (!isPop && !curTab.equals(TAB_TODAY))
			mTabHost.setCurrentTab(0);
		/**
		 * Or perform exit
		 */
		else if (!isPop && curTab.equals(TAB_TODAY)) {
			if (isBack)
				super.onBackPressed();
			else {
				isBack = true;
				Toast.makeText(this, getString(R.string.click_back_again_to_exit), Toast.LENGTH_SHORT).show();
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						isBack = false;
					}
				}, 2000);
			}
		}
	}

	/**
	 * Work around with onActivityResult. Android has a bug that activity cannot
	 * delivery activity result to its nested fragment (fragment managed by
	 * child fragment manager) You must implement your onActivityResult inside
	 * nested fragment's onResume method. Do not forget to set mRequestCode=-1
	 * and mResultIntent=null after things done.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.w(getClass().getSimpleName(), "onActivityResult " + requestCode);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQUEST_LOGIN:
			case REQUEST_EDITCAMERA:
			case REQUEST_EDITLIBRARY:
			case REQUEST_EDITCROP:
			case REQUEST_EDITPOST:
			case REQUEST_NEWPOST:
				mRequestCode = requestCode;
				mResultIntent = data;
				break;
			case REQUEST_CAMERA:
				Intent intent1 = new Intent(MainActivity.this, CreatePostActivity.class);
				intent1.putExtra(CreatePostActivity.EXTRA_IMAGEPATH, mConfig.getImageTemp());
				intent1.putExtra(CreatePostActivity.EXTRA_REQUESTCODE, REQUEST_CAMERA);
				intent1.putExtra(CreatePostActivity.EXTRA_TEMPIMAGE, mConfig.getImageTemp());
				intent1.putExtra(CreatePostActivity.EXTRA_USERID, mUser.Id);
				intent1.putExtra(CreatePostActivity.EXTRA_TYPE, CreateType.CREATE);
				startActivityForResult(intent1, REQUEST_NEWPOST);
				break;
			case REQUEST_LIBRARY:
				Uri img = data.getData();
				String path = "";
				if (img.toString().startsWith("content://com.android.gallery3d.provider"))
					img = Uri.parse(img.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
				path = getRealPathFromURI(img);
				path = (path == null || path.length() == 0) ? img.toString() : path;
				Log.w(getClass().getSimpleName(), path);
				Intent intent2 = new Intent(MainActivity.this, CreatePostActivity.class);
				intent2.putExtra(CreatePostActivity.EXTRA_IMAGEPATH, path);
				intent2.putExtra(CreatePostActivity.EXTRA_REQUESTCODE, REQUEST_LIBRARY);
				intent2.putExtra(CreatePostActivity.EXTRA_TEMPIMAGE, mConfig.getImageTemp());
				intent2.putExtra(CreatePostActivity.EXTRA_USERID, mUser.Id);
				intent2.putExtra(CreatePostActivity.EXTRA_TYPE, CreateType.CREATE);
				startActivityForResult(intent2, REQUEST_NEWPOST);
				break;
			default:
				break;
			}
		}
	}

	/**
	 * Activity attached to window
	 */
	@Override
	public void onAttachedToWindow() {
		Log.w(getClass().getSimpleName(), "onAttachedToWindow ");
		super.onAttachedToWindow();

		notifyBadgeChanged();
		
		String savedUser = mPrefs.getString(PrefsDefinition.USER_LANGUAGE, "");
		if (savedUser.length() > 0 && !mOptions.mAutoLogin) {
			mUser = new Gson().fromJson(savedUser, Member.class);
			mPrefs.edit().putString(PrefsDefinition.USER_LANGUAGE, "").commit();
		}

		int returnTo = getIntent().getIntExtra(EXTRAS_TABRESUME, -1);
		if (returnTo > 0) {
			mTabHost.setCurrentTab(returnTo);
			getIntent().removeExtra(EXTRAS_TABRESUME);
		}
	}

	/**
	 * Get base fragment by tag
	 * 
	 * @param tag
	 */
	public BaseFragment getBase(String tag) {
		return (BaseFragment) getSupportFragmentManager().findFragmentByTag(tag);
	}

	/**
	 * Get current base fragment
	 * 
	 * @return
	 */
	public BaseFragment getCurrentBase() {
		String curTab = mTabHost.getCurrentTabTag();
		if (curTab.equals(TAB_TODAY))
			return getBase(TAB_TODAY);
		if (curTab.equals(TAB_WEEKLY))
			return getBase(TAB_WEEKLY);
		if (curTab.equals(TAB_STYLER))
			return getBase(TAB_STYLER);
		if (curTab.equals(TAB_SELF))
			return getBase(TAB_SELF);
		return getBase(TAB_SETTINGS);
	}

	/**
	 * Change title of current screen
	 * 
	 * @param title
	 */
	public void changeTitle(String title) {
		mTxtTitle.setText(Html.fromHtml(title));
	}
	public void changeTitle(int titleRes) {
		mTxtTitle.setText(Html.fromHtml(getString(titleRes)));
	}

	/**
	 * Get the language name, language code...
	 * @return
	 */
	public String getLanguageName() {
		return getResources().getStringArray(R.array.language)[mOptions.mLanguage];
	}
	public String getLanguageCode() {
		return getResources().getStringArray(R.array.languages_code)[mOptions.mLanguage];
	}
	
	public Locale getCurrentLocale() {
		return getResources().getConfiguration().locale;
	}
	
	/**
	 * Change the app's language (locale) by language number
	 * @param languageOption
	 */
	public void changeLanguage(int languageOption) {
		Locale locale = Locale.KOREA;
		switch (languageOption) {
		case 0:
		case 1:
			locale = Locale.KOREA;
			break;
		case 2:
			locale = Locale.ENGLISH;
			break;
		case 3:
			locale = new Locale("vi_VN");
			break;
		default:
			break;
		}
		Locale.setDefault(locale);
        Configuration appConfig = getApplicationContext().getResources().getConfiguration();
        appConfig.locale = locale;
        getApplicationContext().getResources().updateConfiguration(appConfig,
        		getApplicationContext().getResources().getDisplayMetrics());
	}

	/**
	 * Image loader callback instance using for all ImageView
	 */
	public static final UrlImageViewCallback	mImageLoaderCallback	= new UrlImageViewCallback() {
																			@Override
																			public void onLoaded(ImageView arg0,
																					Bitmap arg1, String arg2,
																					boolean arg3) {

																			}
																		};

	/**
	 * Implement OnTabChangedListener
	 * 
	 * @param tabId
	 */
	@Override
	public void onTabChanged(String tabId) {
		if (tabId.equals(TAB_SELF) && mUser == null) {
			mTabHost.setCurrentTab(mPrevTab);
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra(EXTRAS_TABRESUME, 3);
			startActivityForResult(intent, REQUEST_LOGIN);
		} else {
			mPrevTab = mTabHost.getCurrentTab();
		}
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mBadgeReceiver);
		super.onDestroy();
	}

	/**
	 * Reload badge number, play badge appear animation
	 */
	public void notifyBadgeChanged() {
		Log.w(getClass().getSimpleName(), "notifyBadgeChanged");
		mTxtBadge.clearAnimation();
		mTxtBadge.setText(mBadgeCount + "");
		if (mBadgeCount <= 0)
			mTxtBadge.setVisibility(View.INVISIBLE);
		else {
			mTxtBadge.setVisibility(View.VISIBLE);
			mTxtBadge.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bounce_drop));
		}
		/*
		 * Edit shared preferences in another task to prevent UI freeze
		 */
		new AsyncTask<Integer, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Integer... params) {
				mPrefs.edit().putInt(PrefsDefinition.BADGECOUNT, mBadgeCount).commit();
				return null;
			}
		}.execute();
	}

	/**
	 * Get the image path from uri. Used after received result from ACTION_PICK intent
	 * @param contentUri
	 * @return
	 */
	public String getRealPathFromURI(Uri contentUri) {
		String path = null;
		String[] proj = { MediaStore.MediaColumns.DATA };
		Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
		if (cursor.moveToFirst()) {
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
			path = cursor.getString(column_index);
		}
		cursor.close();
		return path;
	}

	/**
	 * Implement OnClickListener for views
	 */
	@Override
	public void onClick(View v) {
		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		View view = getCurrentFocus();
	    if (view != null)
	    	inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		switch (v.getId()) {
		case R.id.main_btnBack:
			onBackPressed();
			break;
		case R.id.main_btnCamera:
			new GetImageDialogFragment.Builder()
			.setCallback(this, ListenerType.ACTIVITY)
			.build().show(getSupportFragmentManager());
			break;
		case R.id.main_btnEdit:
			EditDialogFragment.newInstance().show(getSupportFragmentManager());
			break;
		case R.id.main_btnNotify:
			mNotiWindow.showAsDropDown(mBtnNotify);
			// Reset notification badge
			mBadgeCount = 0;
			notifyBadgeChanged();
			GCMIntentService.NUMBER = 0;
			BadgeHelper.updateBadge(this, mBadgeCount);
			// Delete notification from status bar
			NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			manager.cancel(GCMIntentService.NOTIFICATION_ID);
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onNewIntent(final Intent intent) {
		super.onNewIntent(intent);
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				notificationClicked(intent);
			}
		}, 500);
	}

	@Override
	public void takeByCamera() {
		Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(mConfig.getImageTemp())));
		startActivityForResult(intent, MainActivity.REQUEST_CAMERA);
	}

	@Override
	public void takeByLibrary() {
		Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setType("image/*");
		startActivityForResult(intent, MainActivity.REQUEST_LIBRARY);
	}

	@Override
	public void edit() {
		Intent intent = new Intent(this, CreatePostActivity.class);
		intent.putExtra(CreatePostActivity.EXTRA_POSTID, mStylePost.Id);
		intent.putExtra(CreatePostActivity.EXTRA_POSTCONTENT, mStylePost.Content);
		intent.putExtra(CreatePostActivity.EXTRA_POSTIMAGE, mStylePost.Image);
		intent.putExtra(CreatePostActivity.EXTRA_USERID, mUser.Id);
		intent.putExtra(CreatePostActivity.EXTRA_REQUESTCODE, REQUEST_EDITPOST);
		intent.putExtra(CreatePostActivity.EXTRA_TYPE, CreateType.EDIT);
		intent.putExtra(CreatePostActivity.EXTRA_TEMPIMAGE, mConfig.getImageTemp());
		startActivityForResult(intent, MainActivity.REQUEST_EDITPOST);
	}

	@Override
	public void delete() {
		new ConfirmDialogFragment.Builder()
		.setMessage(getString(R.string.do_you_want_to_delete_this_post))
		.setType(Type.ACTIVITY)
		.build().show(getSupportFragmentManager());
	}

	@Override
	public void yesClick() {
		new AsyncTask<Integer, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Integer... params) {
				try {
					return new Service().deletePost(mUser.Id, mStylePost.Id) > 0;
				} catch (IOException | XmlPullParserException e) {
					e.printStackTrace();
					return false;
				}
			}
			@Override
			protected void onPostExecute(Boolean result) {
				if (result) {
					Toast.makeText(MainActivity.this, R.string.delete_successful, Toast.LENGTH_SHORT).show();
					getCurrentBase().popAllFragment();
				}
				else
					Toast.makeText(MainActivity.this, R.string.delete_failed, Toast.LENGTH_SHORT).show();
			};
		}.execute();
	}

	@Override
	public void noClick() {
	}
	
	private void notificationClicked(Intent intent) {
		if (!intent.hasExtra(GCMIntentService.DATA_TAG))
			return;
		Notify noti = new Gson().fromJson(intent.getStringExtra(GCMIntentService.DATA_TAG), Notify.class);
		/*
		 * Find the notification in list
		 */
		for (Notify n : mListNotify)
			if (n.Id == noti.Id) {
				noti = n;
				break;
			}
		
		mBadgeCount = 0;
		notifyBadgeChanged();
		BadgeHelper.updateBadge(this, mBadgeCount);
		GCMIntentService.NUMBER = 0;
		mPrefs.edit().putInt(PrefsDefinition.BADGECOUNT, mBadgeCount).commit();
		
		noti.Unread = 0;
		
		final int notiId = noti.Id;
		new AsyncTask<Integer, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Integer... params) {
				try {
					new Service().readNotification(notiId);
				} catch (IOException | XmlPullParserException e) {
					e.printStackTrace();
				}
				return null;
			}
		}.execute();
		if (noti.Type == 1)
			getCurrentBase().replaceFragment(MemberPostFragment.newInstance(noti.PostID), true);
		if (noti.Type == 2)
			getCurrentBase().replaceFragment(MemberPostFragment.newInstance(noti.PostID), true);
		if (noti.Type == 3)
			getCurrentBase().replaceFragment(MemberPostFragment.newInstance(noti.PostID), true);
		if (noti.Type == 4) {
			FriendListFragment fragment = new FriendListFragment();
			Bundle bundle = new Bundle();
			bundle.putInt(FriendListFragment.ARG_RESUMETAB, 1);
			fragment.setArguments(bundle);
			getCurrentBase().replaceFragment(fragment, true);
		}
		
		intent.removeExtra(GCMIntentService.DATA_TAG);
	}

	/**
	 * Used to get logged in member info
	 * 
	 * @param idmem
	 */
	public void getLoggedMemberInfo(final int idmem, final MyCallable mCall) {
		new AsyncTask<Integer, Integer, Boolean>() {
			ProgressDialogFragment	mProgress	= new ProgressDialogFragment.Builder()
														.setTitle(getString(R.string.loading))
														.setMessage(getString(R.string.please_wait)).build();

			@Override
			protected void onPreExecute() {
				mProgress.show(getSupportFragmentManager());
				mOptions = new Gson().fromJson(mPrefs.getString(PrefsDefinition.OPTION, ""), Options.class);
			}

			@Override
			protected Boolean doInBackground(Integer... params) {
				try {
					mUser = new Service().getInfoMemberById(idmem, -1);
					return true;
				} catch (IOException | XmlPullParserException e) {
					return false;
				}
			}

			@Override
			protected void onPostExecute(Boolean result) {
				mProgress.dismiss();
				if (!result)
					Toast.makeText(MainActivity.this, R.string.cannot_connect_to_server, Toast.LENGTH_SHORT).show();
				else if (mCall != null)
					mCall.call();
				if (mOptions.mAutoLogin)
					mPrefs.edit().putString(PrefsDefinition.USER, (mUser != null) ? new Gson().toJson(mUser) : "")
							.commit();
			}
		}.execute();
	}
}
